package com.tsxy.controller.administrator;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsxy.common.APIResult;
import com.tsxy.entity.Files;
import com.tsxy.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/file")
public class UploadController {

    /*@Value("${spring.servlet.multipart.location}")
    //从配置文件中读取一个值
    private String path;*/

    @Value("${files.upload.path}")
    private String filePath;

    @Autowired
    private FileMapper fileMapper;

    /*@PostMapping("/api/upload")
    public APIResult upload(MultipartFile file){
        String fileName = UploadUtil.save(file, path);
        return APIResult.success(fileName);
    }*/

    /**
     * 文件上传接口
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public APIResult upload2(@RequestParam MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String type = FileUtil.extName(filename);
        long size = file.getSize();
        //先存入磁盘
        File file1 = new File(filePath);
        if ( !file1.exists()){ //判断文件目录是否存在，不存在就自己创建
            file1.mkdirs();
        }
        String uuid = IdUtil.fastSimpleUUID(); //定义文件的标识码
        String fileUUID = uuid + StrUtil.DOT + type;
        File uploadFile = new File(filePath + fileUUID);
        //上传文件
        file.transferTo(uploadFile);
        //获取上传上的文件的Md5
        String md5 = SecureUtil.md5(uploadFile);
        //根据MD5查询文件
        QueryWrapper<Files> queryWrapper = new QueryWrapper<Files>();
        queryWrapper.eq("md5",md5);
        List<Files> filesList = fileMapper.selectList(queryWrapper);
        Files selectOne =filesList.size() == 0 ? null : filesList.get(0);
        String url =null;
        //如果数据库里存在内容一样的文件
        if ( selectOne!= null){
            //获取一样文件的下载路径
            url = selectOne.getUrl();
            //将此次上传的重复的文件删除
            uploadFile.delete();
        }else {
            url = "http://localhost:8000/bookmall/file/" + fileUUID;
        }
        // http://localhost:8000/bookmall/file/3927804cefdb4d5e9a502861eeafe05d.jpg
        //存储数据库
        Files files = new Files();
        files.setName(filename);
        files.setType(type);
        files.setSize(size / 1024);
        files.setUrl(url);
        files.setMd5(md5);
        String[] split = url.split("/");
        String localName = split[split.length - 1];
        files.setLocalName(localName);
        int insert = fileMapper.insert(files);
        return APIResult.success(files);
    }

    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        //根据文件的唯一标识找文件
        File file = new File(filePath+fileUUID);
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("content-disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        os.write(FileUtil.readBytes(file));
        os.flush();
        os.close();
    }
    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public APIResult findPage(@RequestParam Integer pageNum,
                              @RequestParam Integer pageSize,
                              @RequestParam(defaultValue = "") String name) {
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete",false);
        if ( ! "".equals(name)){
            queryWrapper.like("name",name);
        }
        Page<Files> page = new Page<>(pageNum, pageSize);
        return APIResult.success(fileMapper.selectPage(page, queryWrapper));
    }
    //根据id删除
    @DeleteMapping("/{id}")
    public APIResult delete(@PathVariable Integer id) {
        Files files = fileMapper.selectById(id);
        files.setIsDelete(true);
        return APIResult.success(fileMapper.updateById(files));
    }
    //批量删除
    @PostMapping("/del/batch")
    public APIResult deleteBath(@RequestBody List<Integer> ids){
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        List<Files> files = fileMapper.selectList(queryWrapper);
        for (Files file: files
             ) {
            file.setIsDelete(true);
            fileMapper.updateById(file);
        }
        return APIResult.success();
    }

    @PostMapping("/update")
    public APIResult save(@RequestBody Files files){
        return APIResult.success(fileMapper.updateById(files));
    }
}
